import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/base_entity.dart';
import 'package:flutter_ncsjqz_getx/model/commodity_details_entity.dart';
import 'package:flutter_ncsjqz_getx/model/order_submit_entity.dart';
import 'package:flutter_ncsjqz_getx/model/submit_order_entity.dart';
import 'package:flutter_ncsjqz_getx/page/my/order/order_view.dart';
import 'package:flutter_ncsjqz_getx/util/pay_auth_share_util.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';

class OrderLogic extends GetxController {
  // 0微信支付 1支付宝支付 / 接口所用：(1:微信支付 2:支付宝)
  int payType = 0;
  // 焦点控制
  FocusNode focusNode = FocusNode();
  // 备注
  TextEditingController textEditingController = TextEditingController();
  // 选择的商品信息
  CommodityDetailsData? commodityDetailData;
  // 选择的商品sku信息
  CommodityDetailsDataSkuList? commodityDetailsDataSkuList;
  // 电子签名文件地址
  String signPath = "";
  // 订单信息
  SubmitOrderData? submitOrderData;
  // 微信监听流
  StreamSubscription? streamSubscription;

  /// 选择支付方式
  setPayType(int value){
    payType = value;
    update();
  }

  /// 提交订单
  Future<SubmitOrderData?> submitOrder()async{
    OrderSubmitEntity orderSubmitEntity =OrderSubmitEntity();
    double orderActualTotal = commodityDetailData!.price!.toDouble();
    orderSubmitEntity.commodityCount = commodityDetailData!.amount;
    orderSubmitEntity.commodityId = commodityDetailData!.commodityId;
    orderSubmitEntity.shopId =commodityDetailData!.shopId;
    orderSubmitEntity.skuId =commodityDetailsDataSkuList!.skuId;
    orderSubmitEntity.orderReduceAmount = 0.0;
    orderSubmitEntity.orderActualTotal = (commodityDetailsDataSkuList!.oriPrice! * commodityDetailData!.amount!).toDouble();
    orderSubmitEntity.orderRemark =textEditingController.value.text;
    orderSubmitEntity.orderTotal = (commodityDetailsDataSkuList!.oriPrice! * commodityDetailData!.amount!).toDouble();
    orderSubmitEntity.orderVos =[];
    orderSubmitEntity.isCoupon = false;
    orderSubmitEntity.orderPayBatchTotal =orderActualTotal;
    SubmitOrderEntity submitOrderEntity = await DioService<SubmitOrderEntity>().submitOrder(orderSubmitEntity);
    submitOrderData = submitOrderEntity.data;
    return submitOrderData;
    // if(baseBeanEntity.code==0){
    //   // orderNos=[baseBeanEntity.data.orderNo];
    //   // payAmount=baseBeanEntity.data.price;
    // }
  }

  /// 对已提交并签名的订单进行支付
  orderPay() async{
    BaseEntity submitOrderEntity = await DioService<BaseEntity>().payOrder({
      "orderNos": [submitOrderData!.orderNo],
      "payAmount": submitOrderData!.price,
      "payType": payType+1,
      "payTypeName": "${payType==1?'微信支付':'支付宝支付'}",
    });
    if(submitOrderEntity.code==0 && submitOrderEntity.data!=null){
      // 微信支付
      if(submitOrderEntity.data["payType"] == 1){
        PayUtil.wxPay(WxModel.toFormat(submitOrderEntity.data["data"]),);
      }else{
        // 支付宝支付
        PayUtil.alibabaPay(submitOrderEntity.data["data"],onCall: (v){
          if(v==0) {
            toast("支付成功");
            // Get.back();
          }
        });
      }
    }
  }

  /// 订阅微信操作
  wxEvent(){
    streamSubscription = weChatResponseEventHandler.listen((event) async {
      // 0	成功	展示成功页面
      // -1	错误	可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
      // -2	用户取消	无需处理。发生场景：用户不支付了，点击取消，返回APP。
      print('微信：${event.errCode}');
      if(event.errCode == 0){
        toast("支付成功");
        Get.to(()=> OrderManagePage(currentIndex: 2,));
      }else if(event.errCode == -2){
        toast("取消了支付，支付失败");
      }else{
        toast("支付失败,微信配置存在错误！请联系管理员");
      }
    });
  }
}
